﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using SS.LNDX.Service.Core.Model;
using SS.LNDX.Service.Core.Provider;
using Dapper;
using System.Data.SqlClient;
using SiteServer.Plugin;

namespace SS.LNDX.Service.Controllers
{
    [RoutePrefix("content")]
    public class ContentController : ApiController
    {
        private const string Route = "";
        public static SqlConnection conn => new SqlConnection(SiteServer.Plugin.Context.ConnectionString);

        [HttpGet, Route(Route)]
        public IHttpActionResult PageList()
        {
            try
            {
                var request = Context.GetCurrentRequest();
                var siteId = request.GetQueryInt("siteId");
                int pageSize = request.GetQueryInt("pageSize");
                int pageIndex = request.GetQueryInt("pageIndex", 1);
                int state = request.GetQueryInt("state", 0);
                string sortExpression = request.GetQueryString("sort");
                
                if (!request.IsAdminLoggin || !request.AdminPermissions.HasSitePermissions(siteId, "SS.LNDX.Service")) return Unauthorized();

                var parentId = request.GetQueryString("parentId");
                string sqlContent = "";
                string sqlCount = "";
                string whereExpression = $@"siteId={siteId}";

                if (!string.IsNullOrEmpty(parentId))
                {
                    whereExpression += $@" AND parentId={parentId}";
                }

                if(state == 1)
                {
                    whereExpression += $@" AND IsChecked='True'";
                }

                if (state == 2)
                {
                    whereExpression += $@" AND IsChecked='False'";
                }

                sqlContent = $"SELECT * FROM (SELECT ROW_NUMBER() OVER (ORDER BY {sortExpression}) AS RowNum, * FROM ss_lndx_ContentDetails WHERE {whereExpression} ) AS Details WHERE RowNum >= {pageIndex}*{pageSize}+1 AND RowNum <= {pageIndex + 1}*{pageSize}";
                sqlCount = $"SELECT COUNT(*) FROM ss_lndx_ContentDetails WHERE {whereExpression}";

                return Ok(new { count = conn.QuerySingle<int>(sqlCount), result = conn.Query<dynamic>(sqlContent) });

            }
            catch (Exception ex)
            {
                return InternalServerError(ex);
            }
        }

        [HttpGet, Route("valid")]
        public IHttpActionResult Get([FromUri] int parentId, [FromUri] int userId)
        {
            string sql = $"SELECT * FROM ss_lndx_ContentDetails where parentId={parentId} and siteId=1 and isChecked='true' and tags<>'接读' and (remainCount>0 or remainCount is null) and id not in (select contentid from ss_lndx_enrollment where userId={userId})";
            //string sql = $"SELECT * FROM ss_lndx_ContentDetails";
            return Ok(conn.Query<dynamic>(sql));

        }

        [HttpGet, Route("{id}/enrollments")]
        public IHttpActionResult GetEnrollments([FromUri] int id)
        {
            string sql = $"SELECT * FROM  ss_lndx_EnrollmentDetails where ContentId={id}";
            return Ok(conn.Query<dynamic>(sql));
        }

        [HttpGet, Route("count")]
        public IHttpActionResult GetCount()
        {
            var request = Context.GetCurrentRequest();
            var siteId = request.GetQueryInt("siteId");
            string channelName = request.GetQueryString("cname");

            string whereExpression = $@"SiteId={siteId}";
            if(channelName == "course")
            {
                whereExpression += $@" AND ChannelName<>'活动'";
            }
            if (channelName == "activity")
            {
                whereExpression += $@" AND ChannelName='活动'";
            }


            string sql = $"SELECT COUNT(*) FROM ss_lndx_ContentDetails WHERE {whereExpression}";
            return Ok(new { count = conn.QuerySingle<int>(sql) });
        }

        [HttpGet, Route("search")]
        public IHttpActionResult Search()
        {
            var request = Context.GetCurrentRequest();
            var siteId = request.GetQueryInt("siteId");
            string key = request.GetQueryString("key");
            string keyword = request.GetQueryString("keyword");

            string whereExpression = $@"SiteId={siteId}";
            if (key == "title")
            {
                whereExpression += $@" AND Title Like '%{keyword}%'";
            }

            string sqlContent = $"SELECT * FROM ss_lndx_ContentDetails WHERE {whereExpression} ORDER BY ID DESC";
            string sqlCount = $"SELECT COUNT(*) FROM ss_lndx_ContentDetails WHERE {whereExpression}";

            return Ok(new { count = conn.QuerySingle<int>(sqlCount), result = conn.Query<dynamic>(sqlContent) });
        }
    }
}
